package cn.apthink.calendar;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.apthink.utility.Util;
import lombok.Data;

@Data
public class WorkCalendarHelper {
	private static WorkCalendar defaultCalendar;
	private DepartmentHelper departmentHelper;
	private List<WorkCalendar> lstWorkcalendar;

	private static  WorkCalendar getDefaultCalendar() {
		if (defaultCalendar==null) {
			defaultCalendar = new WorkCalendar();
			defaultCalendar.setStartDate(LocalDate.MIN);
			defaultCalendar.setWeekTemplateId("week-template-default");
		}
		return defaultCalendar;
	}

	private List<WorkCalendar> getWorkCalendarByDeparment(String departmentId) {
		return lstWorkcalendar.stream().filter(x -> {
			return x.getDepartmentId().equals(departmentId);
		}).collect(Collectors.toList());
	}

	/**
	 * 返回生产单位的工作日历模版数据（如未指定，递归返回父类的工作日历模板数据）
	 * 
	 * @param uid
	 * @return
	 * @throws RuntimeException
	 */
	public List<WorkCalendar> getWorkCalendar(String departmentId) throws RuntimeException {
		List<WorkCalendar> result = new ArrayList<WorkCalendar>();
		String id = departmentId;
		while (!Util.isEmpty(id)) {
			List<WorkCalendar> ts = getWorkCalendarByDeparment(id);
			if (!Util.isEmpty(ts)) {
				// David：只添加父类中工作日历开始日期小于子类工作日历记录
				if (result.size() > 0) {
					LocalDate minStart = result.stream().map(WorkCalendar::getStartDate)
							.min(Comparator.naturalOrder()).get();
					ts = ts.stream().filter(x -> {
						return x.getStartDate().compareTo(minStart) < 0;
					}).collect(Collectors.toList());
				}
				result.addAll(ts);
			}
			id = departmentHelper.getPid(id);
		}
		result.sort((a, b) -> {
			return a.getStartDate().compareTo(b.getStartDate());
		});
		return result;
	}

	public static WorkCalendar getWorkCalendar(List<WorkCalendar> list, LocalDate current) {
		for (int i=list.size()-1;i>=0;i--) {
			if (!list.get(i).getStartDate().isAfter(current)) {
				return list.get(i);
			}
		}
		return getDefaultCalendar();
	}
	
	public static WorkCalendarHelper testData() {
		WorkCalendarHelper helper = new WorkCalendarHelper();
		helper.setLstWorkcalendar(WorkCalendar.testDatas());
		DepartmentHelper departmentHelper = new DepartmentHelper();
		departmentHelper.setLstDepartment(Department.testDatas());
		helper.setDepartmentHelper(departmentHelper);
		return helper;
	}
}
